import { existsSync, readFileSync } from 'fs'
import { readFile, writeFile } from 'fs/promises'
import { resolve } from 'path'

const root = process.cwd()
const storeName = `project_id_map.json`
const storePath = resolve(root, storeName)

export const initStorage = async () => {
  const exist = existsSync(storePath)
  if (!exist) {
    await writeFile(storePath, JSON.stringify({}), { encoding: 'utf-8' })
  }
}

export const getStorage = (): Record<string, string> => {
  const text = readFileSync(storePath, 'utf-8')
  return JSON.parse(text)
}

export const setStorage = async (id: string, path: string) => {
  const Json = getStorage()
  Json[id] = path

  const text = JSON.stringify(Json)
  await writeFile(storePath, text, { encoding: 'utf-8' })

  return true
}

export const paths = {
  root: '',
  utils: '',
  views: '',
  components: '',
  assets: '',
  updateRoot(id: string) {
    this.root = getStorage()[id]

    this.utils = `${this.root}\\src\\utils`
    this.views = `${this.root}\\src\\views`
    this.components = `${this.root}\\src\\components`
    this.assets = `${this.root}\\src\\assets`
  }
}
